package com.xzh.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzh.model.Students;
import com.xzh.service.StudentsService;
import com.xzh.util.JsonResult;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/students")
public class StudentsApi {
    private StudentsService studentsService;
    @Autowired
    public void setStudentsService(StudentsService studentsService){
        this.studentsService = studentsService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> searchAll(@RequestParam(defaultValue = "1") Integer pageNo,
                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                   Students students){

        Page<Students> page = new Page<>(pageNo, pageSize);
        page = studentsService.selectAll(page, students);
        return ResponseEntity.ok(JsonResult.success(page));

    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@Valid @RequestBody Students students){
        boolean result = studentsService.save(students);
        return ResponseEntity.ok(JsonResult.success(result));
    }

    @DeleteMapping
    public ResponseEntity<JsonResult<?>> delete(@RequestBody Integer[] ids){
        int result = studentsService.removeByIds(List.of(ids));
        return ResponseEntity.ok(JsonResult.success(result));
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@Valid @RequestBody Students students){
        boolean result = studentsService.updateById(students);
        if ( result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @GetMapping("/statistics")
    public ResponseEntity<JsonResult<?>> statistics(){
        List<Map<String, Object>> result = studentsService.statistics();
        return ResponseEntity.ok(JsonResult.success(result));
    }

}
